﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace AssignmentsManage.DataClasses
{
    public static class DataLoader
    {
        #region Loading/Saving Methods

        /// <summary>
        /// Opens a file and creates a new DataHolder object to store the data
        /// </summary>
        /// <param name="filePath">Location of the file</param>
        /// <returns>DataHolder with all data in the file</returns>
        public static DataHolder LoadFromFile(string filePath)
        {
            try
            {
                DataHolder openHolder = new DataHolder();

                // these lines do the actual serialization
                XmlSerializer mySerializer = new XmlSerializer(typeof(DataHolder));
                StreamReader myReader = new StreamReader(filePath);
                openHolder = (DataHolder)mySerializer.Deserialize(myReader);
                myReader.Close();

                return openHolder;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Save changes to a file
        /// </summary>
        /// <param name="filePath">Location of the file</param>
        /// <param name="dataObject">DataHolder object containing the data to be saved</param>
        public static void SaveToFile(string filePath, DataHolder dataObject)
        {
            dataObject.LastSave = DateTime.Now;
            XmlSerializer mySerializer = new XmlSerializer(typeof(DataHolder));
            StreamWriter myWriter = new StreamWriter(filePath);
            mySerializer.Serialize(myWriter, dataObject);
            myWriter.Close();
        }

        /// <summary>
        /// Creates a new, file with empty collections.
        /// </summary>
        /// <param name="filePath">Location of the file</param>
        /// <returns>New empty DataHolder object</returns>
        public static DataHolder CreateNewFile(string filePath)
        {
            try
            {
                DataHolder openHolder = new DataHolder();
                SaveToFile(filePath, openHolder);
                return openHolder;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        #endregion
    }
}
